//
//  Detail.m
//  LilyBBS
//
//  Created by 李行 on 11-12-8.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Detail.h"
#import "TFHpple.h"
#import "RegexKitLite.h"
#import "SingleCookie.h"
#import "LogIn.h"
#import "Reachability.h"
#import "ASIHTTPRequest.h"

@implementation Detail

@synthesize WebView,detail,urlString,_replyview,titlestring,requestData,indicatorView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    indicatorView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicatorView.center=CGPointMake(160,160);
    [self.WebView addSubview:indicatorView];
    [indicatorView startAnimating];
    
    //[self.view setBackgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1]];
    [self.WebView setBackgroundColor:[UIColor clearColor]];
    [WebView setDelegate:self];
    [WebView setDataDetectorTypes:UIDataDetectorTypeLink];
    NSString *resourcePath = [ [NSBundle mainBundle] resourcePath];
	NSString *filePath = [resourcePath stringByAppendingPathComponent:@"index.html"];
	NSString *htmlString=[[NSString alloc] initWithContentsOfFile:filePath  encoding:NSUTF8StringEncoding error:nil]; 
	[WebView loadHTMLString:htmlString  baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
    [htmlString release];
    
    reply = [[UIBarButtonItem alloc] 
             initWithTitle:@"回复"                                            
             style:UIBarButtonItemStyleBordered 
             target:self 
             action:@selector(reply)];
    self.navigationItem.rightBarButtonItem = reply;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL *requestURL =[ [ request URL ] retain ]; 
    if(([[requestURL scheme]isEqualToString: @"http"]||[[requestURL scheme]isEqualToString:@"https"]) 
        && (navigationType == UIWebViewNavigationTypeLinkClicked)){ 
        return ![[UIApplication sharedApplication]openURL:[requestURL autorelease]]; 
    } 
    [requestURL release]; 
    return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    
    /*indicatorView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicatorView.center=CGPointMake(self.view.center.x,240);
    [self.view addSubview:indicatorView];
    [indicatorView startAnimating];*/
    
    NSURL* url = [[NSURL alloc] initWithString:self.urlString];
    NSData* data = [[NSData alloc] initWithContentsOfURL:url];
    [self getDetail:data];
    [data release];
    [url release];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //[indicatorView stopAnimating];
    //[indicatorView setHidden:YES];
    
    /*NSString* imageSrc = [NSString stringWithString:@"http://bbs.nju.edu.cn/images/bbs.gif"];
    NSString* js = [NSString stringWithFormat:@"document.write(\"<img src='%@'/>\")",imageSrc];
    [WebView stringByEvaluatingJavaScriptFromString:js];*/
    
    NSString *cssPath = [[NSBundle mainBundle] pathForResource:@"style" ofType:@"css"];
    NSString *finalJS = [NSString stringWithFormat:@"document.write(\"<h2>%@</h2>\");",self.titlestring];
    finalJS = [finalJS stringByAppendingFormat:@"var headID = document.getElementsByTagName('head')[0];"
               "var cssNode = document.createElement('link');"
               "cssNode.type = 'text/css';"
               "cssNode.rel = 'stylesheet';"
               "cssNode.href = '%@';"
               "cssNode.media = 'screen';"
               "headID.appendChild(cssNode);"
               ,cssPath];

    NSArray* author1 = [detail objectAtIndex:0];
    NSArray* author2 = [detail objectAtIndex:1];
    NSArray* text    = [detail objectAtIndex:2];
    NSArray* time    = [detail objectAtIndex:3];
    NSArray* ip      = [detail objectAtIndex:4];
    int number = [author1 count];
    for(int i=0;i<number;i++){  
        //finalJS = [finalJS stringByAppendingFormat:@"document.write(\"<a>发信人:%@</a><br>\");",[author1 objectAtIndex:i]];
        finalJS = [finalJS stringByAppendingFormat:@"document.write(\"<a>发信人:%@(%@)</a><br>\");",[author1 objectAtIndex:i],[author2 objectAtIndex:i]];
        finalJS = [finalJS stringByAppendingFormat:@"document.write(\"<a>时间:%@</a><br>\");",[time objectAtIndex:i]];
        finalJS = [finalJS stringByAppendingFormat:@"document.write(\"<h4>%@</h4>\");",[text objectAtIndex:i]];
        finalJS = [finalJS stringByAppendingFormat:@"document.write(\"<a>FROM:%@</a><br>\");",[ip objectAtIndex:i]];
        finalJS = [finalJS stringByAppendingFormat:@"document.write(\"<a>-------------------------------------------------------------</a><br>\");"];
    }
    [WebView stringByEvaluatingJavaScriptFromString:finalJS];
    [indicatorView stopAnimating];
}

//item:(author1,authors2,text,time,ip)
- (void)getDetail:(NSData*) data{
    /*Byte *testByte = (Byte *)[data bytes];
    for(int i=0;i<[data length];i++){
        printf("testByte = %d\n",testByte[i]);
    }
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingASCII);
    NSStringEncoding enc2 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGBK_95);
    NSStringEncoding enc3 = CFStringConvertEncodingToWindowsCodepage(kCFStringEncodingGB_18030_2000);
    
    NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];
    NSLog(@"%@",retString);
    data = [retString dataUsingEncoding:enc3];
    [retStr release];*/
    
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
    NSMutableArray* arr = [[NSMutableArray alloc] init];

    NSArray *authors1 = [xpathParser searchWithXPathQuery:@"//tr/td/a[3]"];
    NSArray* content = [xpathParser searchWithXPathQuery:@"//textarea"];
    
    if ([authors1 count]==0) {
        NSURL* url = [NSURL URLWithString:urlString];
        ASIHTTPRequest* request = [[ASIHTTPRequest alloc]initWithURL:url];
        [request setDelegate:self];
        [request startSynchronous];
        requestData = [request responseData];
        [request release];
        xpathParser = [[TFHpple alloc] initWithHTMLData:requestData];
        NSArray *authors1 = [xpathParser searchWithXPathQuery:@"//tr/td/a[3]"];
        NSArray* content = [xpathParser searchWithXPathQuery:@"//textarea"];
    }
    
    NSMutableArray* authors1arr = [[NSMutableArray alloc] init];
    NSMutableArray* authors2arr = [[NSMutableArray alloc] init];
    NSMutableArray* textarr = [[NSMutableArray alloc] init];
    NSMutableArray* timearr = [[NSMutableArray alloc] init];
    NSMutableArray* iparr = [[NSMutableArray alloc] init];
    
    
	for (TFHppleElement *element in authors1) {
		NSString *strs = [element content];
		[authors1arr addObject:strs];
        //NSLog(@"authors1:%@",strs);
    }    
    
	for (TFHppleElement *element in content) {
		NSString *strs = [element content];
        //NSLog(@"strs:%@",strs);
        //NSLog(@"all:%@",strs);
        NSString* text = [[NSString alloc]init];
        if((text = [strs stringByMatching:@"(?<=\\s\\d{4}\\)\\n{2})[\\w\\W]*(?=--)"])==NULL){//第一种
            if((text = [strs stringByMatching:@"(?<=\\s\\d{4}\\))[\\w\\W]*(?=--)"])==NULL){//第二种
                if((text=[strs stringByMatching:@"(?<=\\s\\d{4}\\)\\n{2})[\\w\\W]*"])==NULL){//第三种
                    if((text=[strs stringByMatching:@"(?<=\\s\\d{4}\\))[\\w\\W]*"])==NULL){//第四种
                        text = @"无法读取数据";
                    }
                }
            }
        }
        //[textarr addObject:text];
        //将空行转换为<br>，以在网页中出现，并删除不必要的空行
        NSString* string = [text stringByReplacingOccurrencesOfRegex:@"(?<=\\r\\n)\\r\\n" withString:@""];
        string = [string stringByReplacingOccurrencesOfRegex:@"^(\\r\\n)*" withString:@""];
        string = [string stringByReplacingOccurrencesOfString:@"\r\n" withString:@"<br>"];
        string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        NSArray* expressions = [NSArray arrayWithObjects:@"[:s]",@"[:O]",@"[:|]",@"[:$]",@"[:X]",@"[:'(]",@"[:-|]",@"[:@]",@"[:P]",@"[:D]",@"[:)]",@"[:(]",@"[:Q]",@"[:T]",@"[;P]",@"[;-D]",@"[:!]",@"[:L]",@"[:?]",@"[:U]",@"[:K]",@"[:C-]",@"[;X]",@"[:H]",@"[;bye]",@"[;cool]",@"[:-b]",@"[:-8]",@"[;PT]",@"[:hx]",@"[;K]",@"[:E]",@"[:-(]",@"[;hx]",@"[:-v]",@"[;xx]", nil];
        
        //NSLog(@"%@",string);
        //将代表表情的字符串转换为<img>标签，以显示表情
        if ([string isMatchedByRegex:@"(?=\\[)[\\w\\W]{2,5}(?<=\\])"]) {
            NSString* expression = [string stringByMatching:@"(?=\\[)[\\w\\W]{2,5}(?<=\\])"];
            int expNumber = [expressions indexOfObject:expression];
            NSString* expName;
            if (expNumber<9) {
                expName = [NSString stringWithFormat:@"00%i",expNumber+1];
            }else{
            expName = [NSString stringWithFormat:@"0%i",expNumber+1];
            }
            //NSLog(@"%@",expName);
            NSString* expPath = [[NSBundle mainBundle] pathForResource:expName ofType:@"gif"];
            NSString* injectedString = [NSString stringWithFormat:@"<img src='%@' />",expPath];
            string = [string stringByReplacingOccurrencesOfString:expression withString:injectedString];
            //NSLog(@"string:%@",string);
        }
        
        //将图片的地址转换为<img>标签，以显示图片
        if ([string isMatchedByRegex:@"(?=http://bbs.nju.edu.cn/file/)[\\w\\W]*(?<=jpg|JPG)"]) {
            NSArray* images = [string componentsMatchedByRegex:@"(?=http://bbs.nju.edu.cn/file/)[\\w\\W]+?(?<=jpg|JPG)"];
            for(NSString* image in images){
                NSString* imageNode = [NSString stringWithFormat:@"<img src='%@' alt='图片获取失败' width='300px' /><br>",image];
                string = [string stringByReplacingOccurrencesOfRegex:image withString:imageNode];
            }
            //NSLog(@"%@",string);
        }
        //将双引号正确显示
        string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"'"];

        //NSLog(@"string:%@",string);
        [textarr addObject:string];
        
        
        NSArray* authordate = [strs componentsMatchedByRegex:@"(?<=\\().*?(?=\\))"];
        NSString* str1 = [[NSString alloc] init];
        NSString* str2 = [[NSString alloc] init];
        switch ([authordate count]) {
            case 1:
                str1 = @"(无法获取作者)";//author2
                str2 = [authordate objectAtIndex:0];//date
                [authors2arr addObject:str1];
                [timearr addObject:str2];
                break;
            case 3:
                str1 = [authordate objectAtIndex:0];//author2
                str2 = [authordate objectAtIndex:1];//date
                [authors2arr addObject:str1];
                [timearr addObject:str1];
                break;
            case 0:
                str1 = @"(无法获取作者)";//author2
                str2 = @"00:00:00";//date
                [authors2arr addObject:str1];
                [timearr addObject:str2];
                break;
            default:
                str1 = [authordate objectAtIndex:0];//author2
                str1 = [str1 stringByReplacingOccurrencesOfString:@"\"" withString:@"'"];
                str2 = [authordate objectAtIndex:1];//date
                [authors2arr addObject:str1];
                [timearr addObject:str2];
                break;
        }
        
        NSString* ip = [strs stringByMatching:@"((2[0-4]\\d|25[0-5]||[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"];
        if(ip!=NULL){
            [iparr addObject:ip];
        }else{
            ip = @"null";
            [iparr addObject:ip];
        }
        //NSLog(@"ip:%@",ip);
    }
    
    [arr addObject:authors1arr];
    [arr addObject:authors2arr];
    [arr addObject:textarr];
    [arr addObject:timearr];
    [arr addObject:iparr];
    
    self.detail = arr;
    
     [authors1arr release];
     [authors2arr release];
     [textarr release];
     [timearr release];
     [iparr release];
     [arr release];
     [xpathParser release];
}

-(void)dealloc{
    [super dealloc];
}

-(void)reply{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    //若未登录，则提示
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"回复提示" message:@"尚未登录，请登录后回复。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        [alert release];
        return;
        //[self dismissModalViewControllerAnimated:YES];
    }
    //Reply* reply = [[Reply alloc] initWithNibName:@"Reply" bundle:nil];
    
    //UINavigationController *replyCon = [[UINavigationController alloc] initWithRootViewController:reply];
    //[self presentModalViewController:replyCon animated:YES];
    _replyview = [[Reply alloc] init];
    [_replyview.view setFrame:CGRectMake(10, -5, 300, 0)];
    [self.view addSubview:_replyview.view];
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:.3];
    [_replyview.view setFrame:CGRectMake(10, -5, 300, 160)];
    [_replyview.replies becomeFirstResponder];
    _replyview.reptitle.text =[NSString stringWithFormat:@"RE:%@-LilyBBS",titlestring];
    _replyview.urlString = self.urlString;
    [_replyview.cancelbtn addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = nil;
    //NSLog(@"urlString:%@",_replyview.urlString);
	[UIView commitAnimations];
}

-(void)cancel:(id)sender{
    [_replyview.replies resignFirstResponder];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    [_replyview.view setFrame:CGRectMake(10, -5, 300, 0)];
    
    [UIView commitAnimations];
    self.navigationItem.rightBarButtonItem = reply;
    
    [_replyview release];
    
    //[self becomeFirstResponder];
    //[self dismissModalViewControllerAnimated:YES];
}

#pragma UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            NSLog(@"logging in...");
            LogIn* login = [[LogIn alloc] initWithNibName:@"LogIn" bundle:nil];
            UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:login];
            [self presentModalViewController:addNavCon animated:YES];
            [login release];
            break;
            
        default:
            break;
    }
}

@end
